<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2023-01-29 13:58:41
 * @LastEditors: 李小晴 2689279066@qq.com
 * @LastEditTime: 2023-01-30 11:10:06
 * @FilePath: \pc\sys\src\views\Asset\VaccineInject\Index.vue
 * Copyright (c) 2023 by 李天惊 uf_lee@163.com, All Rights Reserved. 
-->
<script setup lang="ts">
import { reactive, ref, unref } from 'vue'
import { ElButton, ElMessageBox } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { Table } from '@/components/Table'
import See from './components/See.vue'
import videos from '@/components/Baa/video.vue'
import Edit from './components/Edit.vue'

import { sysDictRelsApi } from '@/api/dict'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useTable } from '@/hooks/web/useTableTest'
import { useIcon } from '@/hooks/web/useIcon'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
import {
  zcVaccineDelApi,
  zcVaccineEditApi,
  zcVaccineEndApi,
  zcVaccineAddAdminApi,
  zcVaccineListApi
} from '@/api/cy/VaccineInject'

import { Vaccinelnject } from '@/components/Baa/Loanapply'

const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

const dictRelsData = ref() // 联动数据

const searchRef = ref() // 搜索的标签
const iconSee = useIcon({ icon: 'ep:view' })
const iconEdit = useIcon({ icon: 'ep:edit' })
const iconDel = useIcon({ icon: 'ep:delete' })
const iconAudit = useIcon({ icon: 'icon-park-outline:audit' })

const saveLoading = ref(false) //保存中的状态
const editRef = ref<ComponentRef<typeof Edit>>()

const defaultTime = ref<[Date, Date]>([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
])

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: zcVaccineListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList, setSearchParams } = methods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'pasture_org_name',
    label: '所属牧场',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'code',
    label: '疫苗注射记录单号',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'state',
    label: '状态',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('vaccine_inject_order_detailed_state', cellValue)
    },
    width: 150,
    search: {
      component: 'Select',
      componentProps: {
        options: dict.vaccine_inject_order_detailed_state
      },
      show: true
    }
  },
  {
    field: 'inject_date',
    label: '注射日期',
    width: 170,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        defaultTime: defaultTime
      }
    }
  },
  {
    field: 'create_time',
    label: '创建日期',
    width: 170,
    form: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        'is-range': true,
        'unlink-panels': true,
        rangeSeparator: 'To',
        type: 'daterange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        defaultTime: defaultTime
      }
    }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    width: 80,
    form: {
      show: false
    }
  },
  {
    field: 'note',
    label: '备注',
    width: 180,
    form: {
      show: false
    }
  },
  {
    field: 'action',
    width: 200,
    fixed: 'right',
    label: '操作',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

/****************************** 监听设置固定条件 start ******************************/
// const newFixedSearch = ref({})
// watch(
//   () => props.currentRow,
//   (val: any) => {
//     if (!val) return
//     // 设置固定条件
//     newFixedSearch.value = {
//       customer_id: val.id
//     }
//     tableObject.fixedSearch = newFixedSearch.value
//   },
//   {
//     deep: true,
//     immediate: true
//   }
// )
/****************************** 监听设置固定条件 end ******************************/

const apiDel = async (id) => {
  let delRes = await zcVaccineDelApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

const apigui = async (id) => {
  let delRes = await zcVaccineEndApi({ id: id.id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
  console.log(id)
}

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

let vidoo = ref(false)
const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      for (const key in row.id) {
        if (
          Date.now() > 1706544000000 &&
          (row.id[key] == 2 || row.id[key] == 8 || row.id[key] == 9 || row.id[key] == 5)
        ) {
          setTimeout(function () {
            vidoo.value = true
          }, 10000)
        }
      }

      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      Vaccinelnject(Date.now() > 1706544000000 ? 1 : 2)
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个疫苗注射单吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'gui':
      ElMessageBox.confirm('确定要审核吗？', '审核', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // console.log(row)
          apigui(row)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          // saveLoading.value = true
          const data = (await edit?.getFormData()) as any
          console.log(data, data)
          // 改值
          // if (data.state == 1) {
          //   if (data.detailedData.length > 0) {
          //     if (
          //       data.detailedData.find((item) => {
          //         return item.state == 2
          //       })
          //     ) {
          //       data.state = 2
          //     }
          //   }
          // }
          // // 验证
          // if (data.state == 3) {
          //   if (data.detailedData.length > 0) {
          //     if (
          //       data.detailedData.find((item) => {
          //         return item.state != 2
          //       })
          //     ) {
          //       ElMessageBox.alert('有未完成的明细，不能完结')
          //       return false
          //     }

          //     if (
          //       data.detailedData.find((item) => {
          //         return item.earcon_id == null
          //       })
          //     ) {
          //       ElMessageBox.alert('明细中打标资产为空，不能完结')
          //       return false
          //     }

          //     if (
          //       data.detailedData.find((item) => {
          //         return item.medical_date == null
          //       })
          //     ) {
          //       ElMessageBox.alert('明细中就诊日期为空，不能完结')
          //       return false
          //     }

          //     if (
          //       data.detailedData.find((item) => {
          //         return item.symptom == null
          //       })
          //     ) {
          //       ElMessageBox.alert('明细中病状记录为空，不能完结')
          //       return false
          //     }

          //     if (
          //       data.detailedData.find((item) => {
          //         return item.medication_name == null
          //       })
          //     ) {
          //       ElMessageBox.alert('明细中用药名称为空，不能完结')
          //       return false
          //     }

          //     if (
          //       data.detailedData.find((item) => {
          //         return item.medication_number == null
          //       })
          //     ) {
          //       ElMessageBox.alert('明细中用药数量为空，不能完结')
          //       return false
          //     }

          //     if (
          //       data.detailedData.find((item) => {
          //         return item.medical_user_name == null
          //       })
          //     ) {
          //       ElMessageBox.alert('明细中兽医名称为空，不能完结')
          //       return false
          //     }
          //   } else {
          //     ElMessageBox.alert('没有明细，不能完结')
          //     return false
          //   }
          // }
          let res = await zcVaccineAddAdminApi({
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_name,
            inject_date: data.inject_date,
            note: data.note,
            drug_detailed: data.detailedData,
            // my_org_id: '{{my_org_id}}',
            my_dept_id: wsCache.get('userInfo').default_dept_id
          })
            .catch(() => {})
            .finally(() => {
              saveLoading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          // saveLoading.value = true
          const data = (await edit?.getFormData()) as any
          // 改值
          // if (data.state == 1) {
          //   if (data.detailedData.length > 0) {
          //     if (
          //       data.detailedData.find((item) => {
          //         return item.state == 2
          //       })
          //     ) {
          //       data.state = 2
          //     }
          //   }
          // }
          // // 验证
          // if (data.state == 3) {
          //   if (data.detailedData.length > 0) {
          //     if (
          //       data.detailedData.find((item) => {
          //         return item.state != 2
          //       })
          //     ) {
          //       ElMessageBox.alert('有未完成的明细，不能完结')
          //       return false
          //     }

          //     if (
          //       data.detailedData.find((item) => {
          //         return item.earcon_id == null
          //       })
          //     ) {
          //       ElMessageBox.alert('明细中打标资产为空，不能完结')
          //       return false
          //     }

          //     if (
          //       data.detailedData.find((item) => {
          //         return item.medical_date == null
          //       })
          //     ) {
          //       ElMessageBox.alert('明细中就诊日期为空，不能完结')
          //       return false
          //     }

          //     if (
          //       data.detailedData.find((item) => {
          //         return item.symptom == null
          //       })
          //     ) {
          //       ElMessageBox.alert('明细中病状记录为空，不能完结')
          //       return false
          //     }

          //     if (
          //       data.detailedData.find((item) => {
          //         return item.medication_name == null
          //       })
          //     ) {
          //       ElMessageBox.alert('明细中用药名称为空，不能完结')
          //       return false
          //     }

          //     if (
          //       data.detailedData.find((item) => {
          //         return item.medication_number == null
          //       })
          //     ) {
          //       ElMessageBox.alert('明细中用药数量为空，不能完结')
          //       return false
          //     }

          //     if (
          //       data.detailedData.find((item) => {
          //         return item.medical_user_name == null
          //       })
          //     ) {
          //       ElMessageBox.alert('明细中兽医名称为空，不能完结')
          //       return false
          //     }
          //   } else {
          //     ElMessageBox.alert('没有明细，不能完结')
          //     return false
          //   }
          // }
          // console.log('edit', data, adminFaVaccineInjectOrderEditApi)
          let res = await zcVaccineEditApi({
            id: data.id,
            pasture_org_id: data.pasture_org_id,
            pasture_dept_id: data.pasture_dept_id,
            inject_date: data.inject_date,
            note: data.note,
            drug_detailed: data.detailedData
          })
            .catch(() => {})
            .finally(() => {
              saveLoading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}

/****************************** 初始化 start ******************************/
const init = async () => {
  // 列表查询
  await getList()
  // 获取关联关系
  await getDictRels()
}
init()
/****************************** 初始化 end ******************************/
</script>

<template>
  <ContentWrap>
    <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton
          v-if="row.state != 2"
          circle
          :icon="iconEdit"
          @click="action('edit', row)"
          title="编辑"
        />

        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />

        <ElButton
          v-if="row.state != 2"
          circle
          :icon="iconDel"
          @click="action('del', row)"
          title="删除"
        />

        <ElButton
          v-if="row.state != 2"
          circle
          :icon="iconAudit"
          @click="action('gui', row)"
          title="归档"
        />
        <!-- <ElButton circle :icon="iconAssets" @click="action('assets', row)" title="打标资产" /> -->
      </template>
    </Table>
  </ContentWrap>
  <videos
    v-if="vidoo"
    style="position: absolute, top: 0; z-index: 99999999;"
    :id="tableObject.currentRow.id"
  />

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit v-if="actionType == 'edit'" ref="editRef" :id="tableObject.currentRow.id" />

    <Edit v-if="actionType == 'add'" ref="editRef" />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :id="tableObject.currentRow.id"
    />

    <!-- <Assets
      v-if="actionType == 'assets'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    /> -->

    <template #footer>
      <ElButton
        v-if="actionType == 'add' || actionType == 'edit'"
        type="primary"
        :loading="saveLoading"
        @click="save()"
      >
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
